import os
import yaml
import json
from loguru import logger
from modules.context import create_global_context

class YamlParser:
    def __init__(self, file_path):
        self.file_path = file_path
        self.mctx = create_global_context()
        self.data = None

    def check_yaml(self):
        # Check if the file exists and is a valid YAML file
        self.mexcels = list()
        self.mdebug  = dict()

        try:
            with open(self.file_path, 'r', encoding='utf-8') as file:
                config = yaml.safe_load(file)
                self.mdebug["json_file"] = config["debug"]["json_file"]
                self.mdebug["json_output"] = os.path.join(self.mctx.yaml_dir, os.path.normpath(config["debug"]['json_output']))
                
                for econfig in config['excels']:
                    excel = dict()
                    excel['path'] = os.path.join(self.mctx.yaml_dir, os.path.normpath(econfig['path']))
                    excel['output'] = os.path.join(self.mctx.yaml_dir, os.path.normpath(econfig['output']))

                    sheets = list()
                    for wsconfig in econfig['sheets']:
                        sheet = dict()
                        slave = dict()

                        sheet['name'] = wsconfig.get('name')
                        sheet['c_code'] = dict()
                        c_code_config = wsconfig.get('c_code')
                        sheet['c_code']['file_name'] = c_code_config.get('file_name')
                        sheet['c_code']['struct_name'] = c_code_config.get('struct_name')
                        sheet['c_code']['struct_ptr_prefix'] = c_code_config.get('struct_ptr_prefix')
                        sheet['c_code']['struct_ptr_suffix'] = c_code_config.get('struct_ptr_suffix')
                        sheet['c_code']['enum_prefix'] = c_code_config.get('enum_prefix')
                        sheet['c_code']['enum_suffix'] = c_code_config.get('enum_suffix')
                        sheet['c_code']['enum_element_prefix'] = c_code_config.get('enum_element_prefix')
                        sheet['c_code']['enum_element_suffix'] = c_code_config.get('enum_element_suffix')
                        sheet['c_code']['slave_code'] = c_code_config.get('slave_code')
                        sheet['c_code']['code_atomic'] = c_code_config.get('code_atomic')
                        sheet['slave_name'] = wsconfig.get('slave_name')
                        sheet['slave_count'] = wsconfig.get('slave_count')
                        sconfig = wsconfig['slave']
                        slave['name'] = sconfig.get("name")
                        slave['count'] = sconfig.get('count')
                        slave['addresses'] = list()
                        for adrconfig in sconfig["addresses"]:
                            slave['addresses'].append(adrconfig.get('address'))
                        sheet['slave'] = slave
                        sheets.append(sheet)
                    excel['sheets'] = sheets
                    logger.debug(json.dumps(excel, indent=4))
                    self.mexcels.append(excel)
            return True
        except yaml.YAMLError:
            logger.error("Error parsing YAML file")
            return False
        except KeyError:
            logger.error("Error parsing YAML file")
            return False
        except TypeError:
            logger.error("Error parsing YAML file")
            return False
        except yaml.YAMLError:
            logger.error("Error parsing YAML file")
            return False

    @property
    def excels(self):
        return self.mexcels
    
    @property
    def debug(self):
        return self.mdebug
    